﻿@page "/Label/{Text?}"
@using LuckyFish.Blog.Models
@using Microsoft.EntityFrameworkCore
@using LuckyFish.Blog.Controls
@inject NavigationManager navigation
@inject IDbContextFactory<BlogContext> DbFactory

<PageTitle>标签</PageTitle>

<h1>标签列表</h1>

@if (Model.Count == 0)
{
    <div>
        <Empty Image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg" Width="133" Text="暂无数据">
            <Template>
                <Button OnClick="@(() => navigation.NavigateTo("/"))">返回到主页</Button>
            </Template>
        </Empty>
    </div>
}
else
{
    @foreach (var item in Model)
    {
        @if (Model.Count == 0)
        {
            <h5>@item.Name</h5>
        }
        else
        {
            <a href="@($"/Label/{item.Name}")" target="_blank">
                <h5>@item.Name</h5>
            </a>
        }
        @foreach (var m in item.Models)
        {
            <ArticleControl Model="m"/>
        }
    }
}

@code {

    [Parameter]
    public string? Text { get; set; }

    private List<ListModel> Model { get; set; } = new();

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        var context = await DbFactory.CreateDbContextAsync();
        if (string.IsNullOrEmpty(Text))
        {
            foreach (var labels in context.LabelLists.Include(list => list.Articles))
            {
                var l = new ListModel() { Name = labels.LabelName };
                l.Models.AddRange(labels.Articles);
                Model.Add(l);
            }
        }
        else
        {
            var label = await context.LabelLists.Include(x => x.Articles)
                .FirstOrDefaultAsync(x => x.LabelName == Text);
            if (label != null)
            {
                var l = new ListModel() { Name = label.LabelName };
                l.Models.AddRange(label.Articles);
                Model.Add(l);
            }
        }
        await context.DisposeAsync();
    }

}